<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<#macro mapperEl value>${r"#{"}${value}}</#macro>
<#if keyColumn??>
    <#list columns as column>
        <#if column.dbColumn == keyColumn><#assign beanKeyField = column.field></#if>
    </#list>
</#if>
<mapper namespace="${nameSpace}">
    <resultMap id="${resultMapId}" type="${entityName}">
    <#list columns as column>
        <result property="${column.field}" column="${column.dbColumn}"/>
    </#list>
    </resultMap>
    <sql id="columns">
    <#list columns as column>${column.dbColumn}<#if column_index != (columns?size - 1)>,</#if></#list>
    </sql>

    <insert id="insert" parameterType="${entityName}" useGeneratedKeys="true"
            keyProperty="${beanKeyField}" keyColumn="${keyColumn}">
        insert into ${tableName}
        (<#list columns as column><#if column.dbColumn != keyColumn>${column.dbColumn}<#if column_index != (columns?size - 1)>
        ,</#if></#if></#list>)
        values(<#list columns as column><#if column.dbColumn != keyColumn><@mapperEl column.field/><#if column_index != (columns?size - 1)>
        ,</#if></#if></#list>)
    </insert>

    <update id="update" parameterType="${entityName}">
        update ${tableName}
        <set>
        <#list columns as column>
            <#if beanKeyField != column.field>
            <if test="${column.field} !=null">${column.dbColumn} = <@mapperEl column.field/>
                <#if column_index != (columns?size - 1)>,</#if></if>
            </#if>
        </#list>
        </set>
        where ${keyColumn} = <@mapperEl beanKeyField/>
    </update>

    <sql id="conditions">
        <where>
        <#list columns as column>
            <if test="${column.field} !=null">and ${column.dbColumn} = ${r"#{"}${column.field}${r"}"}</if>
        </#list>
        </where>
    </sql>
    <select id="findById" parameterType="Map" resultMap="${resultMapId}">
       SELECT
        <include refid="columns"/>
        from ${tableName}
       where ${keyColumn}=<@mapperEl beanKeyField/>
    </select>
    <select id="findAll" resultMap="${resultMapId}">
        select
        <include refid="columns"/>
        from ${tableName}
        <include refid="conditions"/>
    </select>

    <select id="pager" parameterType="Map" resultMap="${resultMapId}">
        select
        <include refid="columns"/>
        from ${tableName}
        <include refid="conditions"/>
        <![CDATA[ order by ${keyColumn} desc limit ${r"#{"}offset${r"}"}, ${r"#{"}limit${r"}"} ]]>
    </select>
    <delete id="delete" parameterType="${entityName}">
        delete from ${tableName} where ${keyColumn} = ${beanKeyField}
    </delete>
</mapper>


